package demo.controller;

import demo.common.ResultJson;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 数据验证失败时的全局错误处理。
     * @param e BindException
     * @return ResultJson 对象，使用 HttpStatus.BAD_REQUEST 指示错误
     */
    @ExceptionHandler(value = BindException.class)
    public ResponseEntity<ResultJson> blogNotFoundException(BindException e) {
        ResultJson resultJson = ResultJson.error(HttpStatus.BAD_REQUEST).message("数据验证失败。");
        for (var v : e.getFieldErrors()) {
            resultJson.data(v.getField(), v.getDefaultMessage());
        }
        return new ResponseEntity<>(resultJson, HttpStatus.BAD_REQUEST);
    }
}
